package com.cloudcross.ssp.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.common.utils.MapBuilder;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.pulgin.mybatis.plugin.PageView;
import com.cloudcross.ssp.service.IAdvertiserDateService;

@Service
public class AdvertiserDataService implements IAdvertiserDateService {

    @Autowired
    private GenericIBatisDao iBatisDao;

    @Override
    public PageView query(PageView pageView, Account t) {
        return null;
    }

    @Override
    public int countByParams(Map<String, Object> paramMap) {
        return 0;
    }

    @Override
    public List<Account> findByParams(Map<String, Object> paramMap, Pager pager) {
        return null;
    }

    @Override
    public List<Account> queryAll(Account t) {
        return null;
    }

    @Override
    public void delete(String id) throws Exception {
    }

    @Override
    public void update(Account t) throws Exception {
    }

    @Override
    public Account getById(String id) {
        return null;
    }

    @Override
    public void add(Account t) throws Exception {
    }

    @Override
    public Map<String, Object> findData(Map<String, Object> paramMap) {
        return null;
    }

    @Override
    public HashMap<String, Object> findTotalImpressionAndClickByAdvertiserId(Map<String, Object> paramMap) {
        return iBatisDao.get("adShowSqlMapper.findTotalImpressionAndClickByAdvertiserId", paramMap);
    }

    @Override
    public HashMap<String, Object> findTotalImpressionAndClickByAgentId(Map<String, Object> paramMap) {
        return iBatisDao.get("adShowSqlMapper.findTotalImpressionAndClickByAgentId", paramMap);
    }

    @Override
    public List<HashMap<String, Object>> findChart(String startDate, String endDate, Long advertiserId, Long agentId) {
        if (advertiserId == -1l) {
            List<HashMap<String, Object>> list = iBatisDao.getList("adShowSqlMapper.findByAgent",
                    MapBuilder.create(HashMap.class).add("startDate", startDate).add("endDate", endDate).add("agentId", agentId).map());
            return list;

        } else {
            List<HashMap<String, Object>> list = iBatisDao.getList("adShowSqlMapper.findByAdvertiser",
                    MapBuilder.create(HashMap.class).add("startDate", startDate).add("endDate", endDate).add("advertiserId", advertiserId).map());
            return list;
        }
    }

    @Override
    public List<HashMap<String, Object>> findChartPage(String startDate, String endDate, Long advertiserId, Long agentId, Pager pager) {
        /**
         * 这里查询分为一段时间和某一天时间
         */
        if (advertiserId == -1l) {
            return iBatisDao.getList("adShowSqlMapper.findByAgentPage", MapBuilder.create(HashMap.class).add("startDate", startDate)
                    .add("endDate", endDate).add("agentId", agentId).add("pager", pager).map());

        } else {
            return iBatisDao.getList("adShowSqlMapper.findByAdvertiserPage", MapBuilder.create(HashMap.class).add("startDate", startDate)
                    .add("endDate", endDate).add("advertiserId", advertiserId).add("pager", pager).map());
        }
    }

    @Override
    public int findCountForChart(String startDate, String endDate, Long advertiserId, Long agentId) {
        if (advertiserId == -1l) {
            return iBatisDao.get("adShowSqlMapper.countByAgent",
                    MapBuilder.create(HashMap.class).add("startDate", startDate).add("endDate", endDate).add("agentId", agentId).map());

        } else {
            return iBatisDao.get("adShowSqlMapper.countByAdvertiser",
                    MapBuilder.create(HashMap.class).add("startDate", startDate).add("endDate", endDate).add("advertiserId", advertiserId).map());
        }
    }

    @Override
    public void requestCcData(String url) {
        Map<String, Object> paramMap =  new HashMap<String, Object>();
        JSONArray data = null;
        try {
            StringBuffer buffer = new StringBuffer();
            // 拼凑get请求的URL字串，使用URLEncoder.encode对特殊和不可见字符进行编码
            String getURL = url;
            URL getUrl = new URL(getURL);
            // 根据拼凑的URL，打开连接，URL.openConnection函数会根据URL的类型，
            // 返回不同的URLConnection子类的对象，这里URL是一个http，因此实际返回的是HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
            // 进行连接，但是实际上get
            // request要在下一句的connection.getInputStream()函数中才会真正发到服务器
            connection.connect();
            // 取得输入流，并使用Reader读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            // 设置编码,否则中文乱码
            String lines;
            while ((lines = reader.readLine()) != null) {
                buffer.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
            JSONObject json = new JSONObject(buffer.toString());
            data = json.getJSONArray("data");
            Map<String, Object> map = null;
            for (int i = 0; i < data.length(); i++) {
                int advertiserId = findDcByCcAdvId(data.getJSONObject(i).getInt("advertiserId"));
                paramMap.put("advertiserId", advertiserId);
                paramMap.put("date", data.getJSONObject(i).getString("date"));
                paramMap.put("impression", data.getJSONObject(i).getInt("shows"));
                paramMap.put("click", data.getJSONObject(i).getInt("clicks"));

                map = iBatisDao.get("adShowSqlMapper.checkCcDataByAdvId", paramMap);
                if (map == null || map.isEmpty()) {
                    iBatisDao.save("adShowSqlMapper.insertCcDataByAdvId", paramMap);
                } else {
                    iBatisDao.save("adShowSqlMapper.updateCcDataByAdvId", paramMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateDcDataToday(Map<String, Object> paramMap) {
        // 删除啊当天的数据
        iBatisDao.save("adShowSqlMapper.deleteDcDataTodayByAdvId", paramMap);
        // 重新插入当天数据
        iBatisDao.save("adShowSqlMapper.insertDcDataTodayByAdvId", paramMap);

    }

    @Override
    public String findAdvsByAgentId(Long agentId) {
        String advIds = "";
        List<Integer> advs = iBatisDao.getList("adShowSqlMapper.findAdvsByAgentId", agentId);
        for (int i = 0; i < advs.size(); i++) {
            if (findCcByDcAdvId(advs.get(i)) != 0) {
                advIds = advIds + advs.get(i).toString() + ",";
            }
        }
        if (advIds.endsWith(",")) {
            advIds = advIds.substring(0, advIds.lastIndexOf(","));
        }
        return advIds;
    }

    @Override
    public Map findCompare(Map<String, Object> paramMap) {
        return null;
    }

    public int findCcByDcAdvId(Integer advertiserId) {
        return iBatisDao.get("adShowSqlMapper.findCcByDcAdvId", advertiserId);
    }

    public int findDcByCcAdvId(Integer ccAdvId) {
        return iBatisDao.get("adShowSqlMapper.adShowSqlMapper", ccAdvId);
    }
}
